import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import dayjs from 'dayjs'


@Injectable()
export class ResponseInterceptor implements NestInterceptor{
	intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
		const request = context.switchToHttp().getRequest<IRequest>()
		const response = context.switchToHttp().getResponse<IResponse>()
		const { method, url, ip } = request;

		return next.handle().pipe(
			map(data => {
				const endTime = Date.now();
				const duration = endTime - request.requestTime;

				response.header('Access-Control-Expose-Headers', 'X-Server-Time');
				response.header('Access-Control-Expose-Headers', 'Accept-Language');
				response.header("X-Server-Time", dayjs().valueOf().toString());

				Logger.log(`IP: ${ip}, Request Method: ${method}, URL: ${url}, Duration: ${duration}ms, TrackId: ${request.trackId}`);

				return {
					data: data,
					code: 0,
					message: '请求成功'
				};
			})
		);
	}
}
